package com.lntea.netty.im.handler;

import com.lntea.netty.im.packet.GroupMessageRequestPacket;
import com.lntea.netty.im.packet.GroupMessageResponsePacket;
import com.lntea.netty.im.packet.common.Session;
import com.lntea.netty.im.packet.common.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;

/**
 * 群消息接收Handler
 */
public class GroupMessageRequestHandler extends SimpleChannelInboundHandler<GroupMessageRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupMessageRequestPacket packet) throws Exception {
        String fromUserId = packet.getFromUserId();
        String groupId = packet.getGroupId();
        String message = packet.getMessage();
        System.out.println(String.format("收到群消息，群组[%s]，发送人[%s]，消息内容[%s]",
                groupId, fromUserId, message));
        ChannelGroup channelGroup = SessionUtil.getChannelGroup(packet.getGroupId());

        // 发送人
        Channel fromUserChannel = SessionUtil.getChannel(fromUserId);
        Session fromUserSession = SessionUtil.getSession(fromUserChannel);

        // 组装响应数据包
        GroupMessageResponsePacket respPacket = new GroupMessageResponsePacket();
        respPacket.setFromUserId(fromUserId);
        respPacket.setFromUserName(fromUserSession.getUserName());
        respPacket.setGroupId(groupId);
        respPacket.setMessage(message);

        // 过滤发送人群发消息
        ChannelMatcher matcher = channel -> !SessionUtil.getSession(channel).getUserId().equals(fromUserId);
        channelGroup.writeAndFlush(respPacket, matcher);
    }
}
